﻿using A_txt;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace txtTEST
{
    public partial class Form1 : Form
    {
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);


        [DllImport("FH.dll", EntryPoint = "sum", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        private static extern int sum(int a, int b);
        //[DllImport("1.dll", CallingConvention = CallingConvention.Cdecl)]
        //[DllImport("ForeignMatter.dll", EntryPoint = "detectForeignMatter", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)] IntPtr ImgSrc
        //[DllImport("ForeignMatter.dll", EntryPoint = "detectForeignMatter", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        //public static extern int detectForeignMatter(IntPtr ImgSrc, int ImgRows, int ImgCols, int ImgChannels, double[] region, double[] parameters, double[] defect);




        [DllImport("ForeignMatter.dll", EntryPoint = "detectForeignMatter", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        private static extern int detectForeignMatter(IntPtr ImgSrc, int ImgRows, int ImgCols, int ImgChannels, double[] region, double[] parameters, double[] defect);
        public Form1()
        {
            InitializeComponent();
        }
        double[] reult_buf = new double[700];
        private void Form1_Load(object sender, EventArgs e)
        {



            //Mat img_buf = new Mat(@"C:\Users\zhang\Desktop\BUF\txtTEST\txtTEST\bin\TU.bmp");
            //double[] reg_buf = new double[4] { 0, 0, img_buf.Cols - 1, img_buf.Rows - 1 };
            //double[] parameters_buf = new double[6] { 2, 30, 10, 10, 30, 1 };
            //double[] reult_buf = new double[700];
            //int a = detectForeignMatter(img_buf.Data, img_buf.Rows, img_buf.Cols, img_buf.Channels(), reg_buf, parameters_buf, reult_buf);


            //int p = sum(9, 6);
            ;
            //int h = add();

            //Bitmap img_buf =(Bitmap)getImage(@"C:\Users\zhang\Desktop\BUF\txtTEST\txtTEST\bin\AF.jpg");
            //this.pictureBox1.Image = img_buf;


            //byte[] buffer = null;
            //Bitmap img_buf = new Bitmap(@"C:\Users\zhang\Desktop\BUF\txtTEST\txtTEST\bin\TU.bmp");
            ////this.pictureBox1.Image = img_buf;
            //IntPtr pval = IntPtr.Zero;
            //BitmapData bd = img_buf.LockBits(new Rectangle(0,0, img_buf.Width, img_buf.Height), ImageLockMode.ReadWrite, img_buf.PixelFormat);
            //pval = bd.Scan0;

            //string buf = "{\"HEAD\":{\"H_GUID\":\"0000\",\"H_RET\":\"00199\",\"H_MSG\":\"接口异常: 执行格式化入参异常：Token不合法：无效的 JSON 基元: 。(0000)\"},\"MAIN\":{}}";
            //JObject Json_buf = (JObject)JsonConvert.DeserializeObject(buf);

            //string strA = Json_buf.GetValue("HEAD").ToString();

            //JObject Json_bufB = (JObject)JsonConvert.DeserializeObject(strA);
            //string strB = Json_bufB.GetValue("H_MSG").ToString();
        }

        int a_buf = 0;
        int b_buf = 0;
        int c1_buf = 0, c2_buf = 0, c3_buf = 0, c4_buf = 0;

        bool[] state = new bool[5] { false, true, false, true, false };
        BindingSource bar_bufview;
        List<String> buf = new List<string>();

        private void Timer1_Tick(object sender, EventArgs e)
        {
            buf.Clear();
            if (bar_bufview!=null)  bar_bufview.Dispose();
            for (int i = 0; i < state.Length; i++)
            {
                if (!state[i])
                {
                    buf.Add($"工位{i+1}已屏蔽。。。");
                }
            }

            bar_bufview = new BindingSource();
            bar_bufview.DataSource = buf;
            listBox1.DataSource = buf;


            //光标跟随
            if (listBox1.Items.Count > 0)
            {
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.SelectedItems.Clear();
            }


        

           
    


            //a_buf = int.Parse(textBox1.Text);
            //if (a_buf == 1)
            //{
            //    b_buf = 1;
            //}
            //else if (a_buf == 2)
            //{
            //    b_buf = 2;
            //}
            //else if (a_buf == 3)
            //{
            //    b_buf = 3;
            //}

            //switch (b_buf)
            //{
            //    case 1:
            //        c2_buf = 0;
            //        c3_buf = 0;
            //        c4_buf = 0;
            //        if (c1_buf==0)
            //        {
            //            c1_buf = 1;
            //            listBox1.Items.Add($"{b_buf}");
            //        }
            //        break;

            //    case 2:
            //        c1_buf = 0;
            //        c3_buf = 0;
            //        c4_buf = 0;
            //        if (c2_buf == 0)
            //        {
            //            c2_buf = 1;
            //            listBox1.Items.Add($"{b_buf}");
            //        }
            //        break;

            //    case 3:
            //        c1_buf = 0;
            //        c2_buf = 0;
            //        c4_buf = 0;
            //        if (c3_buf == 0)
            //        {
            //            c3_buf = 1;
            //            listBox1.Items.Add($"{b_buf}");
            //        }
            //        break;

            //    case 4:
            //        c1_buf = 0;
            //        c2_buf = 0;
            //        c3_buf = 0;
            //        if (c4_buf == 0)
            //        {
            //            c4_buf = 1;
            //            listBox1.Items.Add($"{b_buf}");
            //        }
            //        break;
            //}



            //List<string> buf = new List<string>();
            //for (int i = 0; i < 100; i++)
            //{
            //    buf.Add("ASDFGHJKLQWERTYUIOPZXCVBNM1234564567891234567890QWERTYUIOPASDFGHJKLZXCVBNM_"+i.ToString());

            //}

            
            //bar_bufview.DataSource = buf;
            //listBox1.DataSource = bar_bufview;
            //buf.Clear();




            //string pathA = Application.StartupPath + @"\NotAdb.JPG";
            //string pathB = Application.StartupPath + @"\pic\1-NotAdb.JPG";

            //using (FileStream image = new FileStream(pathA, FileMode.Open))
            //{
            //    Image Image_buf = Image.FromStream(image, true);
            //    pictureBox1.Image = Image_buf;
            //}
            //this.pictureBox1.Image = Image.FromStream(System.Net.WebRequest.Create(pathA).GetResponse().GetResponseStream());

            //try
            //{


            //if (pictureBox1.Image != null)
            //{
            //    pictureBox1.Image.Dispose();
            //    GC.Collect();
            //    GC.WaitForPendingFinalizers();
            //}

            //Image buf_image = getImage(pathA);
            //pictureBox1.Image = buf_image;

            //}
            //catch (Exception ER)
            //{
            //    ;
            //}            
            //buf_image.Dispose();

            //using (FileStream fs = new FileStream(pathA, FileMode.Open, FileAccess.Read))
            //{
            //    byte[] imageByte = new byte[fs.Length];
            //    using (BinaryReader br = new BinaryReader(fs))
            //    {
            //        imageByte = br.ReadBytes(Convert.ToInt32(fs.Length));
            //        using (MemoryStream ms = new MemoryStream(imageByte))
            //        {
            //            using (Bitmap bm = new Bitmap(ms))
            //            {
            //                bm.Save(pathB);
            //            }
            //        }
            //    }
            //}
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            state[0] = false;
            state[1] = false;
        }

        [Serializable]
        public class test_y
        {
            public int state = 0;
            public int state2 = 0;
            public int state3 = 0;
            public int state4 = 0;
            public int state5 = 0;
        }


        private void Button1_Click(object sender, EventArgs e)
        {
            Class1_test _test_Y = new Class1_test();
            _test_Y.state = 1;
            _test_Y.state2 = 1;
            _test_Y.state3 = 1;
            _test_Y.state4 = 1;
            _test_Y.state5 = 1;

            Serialize(_test_Y);
            Class1_test buf = Deserialize<Class1_test>();
            ;
            //try
            //{

            //    using (Mat img_buf = new Mat(@"C:\Users\zhang\Desktop\BUF\txtTEST\txtTEST\bin\2.bmp"))
            //    {
            //        double[] reg_buf = new double[4] { 0, 0, img_buf.Cols - 1, img_buf.Rows - 1 };
            //        double[] parameters_buf = new double[6] { 2, 30, 10, 10, 30, 1 };
            //        int channels = img_buf.Channels();
            //        int a = detectForeignMatter(img_buf.Data, img_buf.Rows, img_buf.Cols, img_buf.Channels(), reg_buf, parameters_buf, reult_buf);
            //    };


            //    //Bitmap buf_img = new Bitmap(@"C:\Users\zhang\Desktop\BUF\txtTEST\txtTEST\bin\2.bmp");
            //    Bitmap buf_img = new Bitmap(@"C:\Users\zhang\Desktop\test2.bmp");
            //    Rectangle rect = new Rectangle(0, 0, buf_img.Width, buf_img.Height);
            //    BitmapData bmpData = buf_img.LockBits(rect, ImageLockMode.ReadWrite, buf_img.PixelFormat);

            //    int bytes = buf_img.Width * buf_img.Height;
            //    IntPtr ptr = Marshal.AllocHGlobal(bytes);
            //    Marshal.StructureToPtr(bmpData.Scan0, ptr, true);

            //    double[] reg_buf2 = new double[4] { 0, 0, buf_img.Width - 1, buf_img.Height - 1 };
            //    double[] parameters_buf2 = new double[6] { 2, 30, 10, 10, 30, 1 };
            //    int b = detectForeignMatter(ptr, buf_img.Height -1, buf_img.Width-1, 3, reg_buf2, parameters_buf2, reult_buf);

            //    buf_img.UnlockBits(bmpData);
            //    Marshal.FreeHGlobal(ptr);
            //}
            //finally
            //{
            //    // img_buf.UnlockBits(bd);
            //}

            //state[0] = true;
            //state[1] = true;

            //string buf = Get("GCC1EW04220600G7");

            //string _buf = Get("GCC1EW04220600CW");

            //string[] hk = new string[2];


            ////获取图片另存图片
            //string pathA =Application.StartupPath + @"\NotAdb.JPG";
            //string pathB = Application.StartupPath + @"\pic\1-NotAdb.JPG";
            //if (!File.Exists(pathA))
            //{
            //    return ;
            //}
            //using (FileStream fs = new FileStream(pathA, FileMode.Open, FileAccess.Read))
            //{
            //    byte[] imageByte = new byte[fs.Length];
            //    using (BinaryReader br = new BinaryReader(fs))
            //    {
            //        imageByte = br.ReadBytes(Convert.ToInt32(fs.Length));
            //        using (MemoryStream ms = new MemoryStream(imageByte))
            //        {
            //            using (Bitmap bm = new Bitmap(ms))
            //            {
            //                bm.Save(pathB);
            //            }
            //        }
            //    }
            //}





            //获取网络图片
            //string url = "http://img.zcool.cn/community/01635d571ed29832f875a3994c7836.png@900w_1l_2o_100sh.jpg";
            //this.pictureBox1.Image = Image.FromStream(System.Net.WebRequest.Create(pathA).GetResponse().GetResponseStream());

            //using (FileStream image = new FileStream(pathA, FileMode.Open))
            //{
            //    Image Image_buf = Image.FromStream(image, true);
            //    pictureBox1.Image = Image_buf;
            //    Image_buf.Save(pathB);
            //}




            ////获取关键字文件
            ////1#
            //string path =Application.StartupPath+ @"\EN_CH.txt";
            //List<string> Str = new List<string>();
            //string[] ReadTextB = File.ReadAllLines(path, Encoding.Default);

            ////2#
            //string[] ReadTextA = new string[9] { "FAIL", "Fail", "Error","!=","Check WifiAddr in server", "Empty SN", "TIMEOUT", "Timeout.Command", "Extend SMLFILE_ID not Match"};

            ////需要查找的LOG信息
            //string pathB = @"C:\Users\zhang\Desktop\syslog1\20220506\82426B8K01C14-085814829.log";
            //string buf = GetTestNgItemMsgByKeyWord(pathB, ReadTextA, ReadTextB);
            //if (buf != string.Empty)
            //{
            //    ;
            //}



            #region 
            //string path = @"C:\Users\zhang\Desktop\syslog1\ng\20220422-9\82328B8J020EC-175345837.log";

            //string[] out_str = null;
            //if (Query_str(path, new string[] { "Connect mobile" }, out out_str) == 0)
            //{
            //    string[] keyEN = null;
            //    string[] keyCH = null;
            //    string str_buf = "FAIL:不通过|TIMEOUT:超时|Timeout.Command:连接超时";
            //    string[] str_bufA = str_buf.Split(new char[3] {'|',':', '=' });


            //    if (str_bufA!=null && str_bufA.Length>0)
            //    {
            //        if (str_bufA.Length % 2 !=0)
            //        {
            //            MessageBox.Show("关键字长度错误");
            //        }
            //        keyEN = new string[str_bufA.Length / 2];
            //        keyCH = new string[str_bufA.Length / 2];
            //        for (int i = 0; i < str_bufA.Length / 2; i++)
            //        {
            //            keyEN[i] = str_bufA[i * 2];
            //            keyCH[i] = str_bufA[i * 2 + 1];
            //        }
            //    }

            //    string str = GetTestNgItemMsgByKeyWord(path, keyEN,keyCH);

            //}
            #endregion
        }

        object image_obj = new object();
        private Image getImage(string path)
        {
            lock (image_obj)
            {
                Image Image_buf = null;
                try
                {
                    if (!File.Exists(path))
                    {
                        return null;
                    }
                    using (FileStream image = new FileStream(path, FileMode.Open))
                    {
                        Image_buf = (Image)Image.FromStream(image, true).Clone();
                    }
                    return Image_buf;
                }
                catch (Exception er)
                {
                    return null;
                }
            }
        }


        CancellationTokenSource cts = null;
        private void Button2_Click(object sender, EventArgs e)
        {
            cts = new CancellationTokenSource();
            ThreadPool.QueueUserWorkItem(new WaitCallback(CanCancelMethod), cts.Token);
            
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            cts.Cancel();
        }

        void CanCancelMethod(Object obj)
        {
            CancellationToken ct = (CancellationToken)obj;
            while (!ct.IsCancellationRequested)
            {
                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine("该线程已取消");
                }
                //就算ct.IsCancellationRequested为真，接下来的代码还是会执行
                //因为该方法并没有ruturn
                Thread.Sleep(1000);
                Console.WriteLine($"子线程{Thread.CurrentThread.ManagedThreadId}结束");
            }

        }

        CancellationTokenSource _cts = null;
        private void Button3_Click(object sender, EventArgs e)
        {
            int a = 0;
            //1s后自动取消线程
            _cts = new CancellationTokenSource(2000);
            //为取消线程注册回调函数
            _cts.Token.Register(() =>
            {
                ;
            });

            Task.Run(() =>
            {
                while (true)
                {
                    Console.WriteLine("开始执行" + a.ToString());
                    a++;
                    Thread.Sleep(1000);
                    if (_cts.Token.IsCancellationRequested)
                    {
                        return;
                    }
                }
            }, _cts.Token);


        }

        private void Button4_Click(object sender, EventArgs e)
        {
            _cts.Cancel();

        }

        int a = 0;
        private void Button6_Click(object sender, EventArgs e)
        {

            a++;
            Task.Run(() =>
            {
              runtask(a.ToString());
            });
            Console.WriteLine("执行中");
        }

        void runtask(string a)
        {
            while (true)
            {
                Console.WriteLine("开始执行" + a);
                Thread.Sleep(1000);
                return;
            }
        }



        List<string> TestNgItem = new List<string>();
        
        /// <summary>
        /// 解析LOG——NG项信息
        /// </summary>
        /// <param name="LogFilePath">log路径</param>
        /// <param name="KeyWordA">查找NG项关键字</param>
        /// <param name="KeyWordB">中文对照关键字</param>
        /// <returns></returns>
        public string GetTestNgItemMsgByKeyWord(string LogFilePath, string[] KeyWordA, string[] KeyWordB)
        {
            try
            {
                string TestNgItemMsg = string.Empty;
                string Text_buf = string.Empty;
                TestNgItem.Clear();

                //判断文件是否存在
                if (!File.Exists(LogFilePath))
                {
                    TestNgItemMsg = LogFilePath + "文件不存在";
                    return TestNgItemMsg;
                }

                //判断是否找到关键字#1信息，未找到开启#2关键字信息查找
                foreach (string _str in File.ReadAllLines(LogFilePath, Encoding.Default))
                {
                    for (int i = 0; i < KeyWordA.Length; i++)
                    {
                        if (_str.Contains(KeyWordA[i]))//搜索指定字符串
                        {
                            Text_buf = _str.Replace("!", "").Replace("&", "");
                            goto T1;
                        }
                    }
                }


            T1:
                //根据关键字翻译
                for (int i = 0; i < KeyWordB.Length; i++)
                {
                    string[] str_buf = null;
                    try { str_buf = KeyWordB[i].Split(new char[1] { ':' }); }
                    catch { str_buf = new string[2] { "FAIL", "null" }; }

                    if (Text_buf.Contains(str_buf[0]))//搜索指定字符串
                    {
                        TestNgItem.Add(KeyWordB[i]);//搜索到的内容存入集合
                        goto T2;
                    }
                }


            T2:
                //如果找到信息将处理信息
                if (TestNgItem.Count > 0)
                {
                    if (!TestNgItem[0].Contains("ERROR"))
                    {
                        int a = TestNgItem[0].IndexOf(']');
                        TestNgItemMsg = TestNgItem[0].Substring((a + 1), (TestNgItem[0].Length - a - 1));
                        if (TestNgItemMsg.IndexOf(' ') == 0)
                        {
                            TestNgItemMsg = TestNgItemMsg.Substring(1, TestNgItemMsg.Length - 1);
                        }
                    }
                    else
                    {
                        TestNgItemMsg = "ERROR";
                    }
                }
                else
                {
                    TestNgItemMsg = "未找到测试失败的信息！";
                }
                return TestNgItemMsg;
            }
            catch (Exception ex)
            {
                return "解析数据异常！详情：" + ex.ToString();
            }
        }



        public int Query_str(string dir, string[] str, out string[] out_str)
        {
            try
            {
                List<string> Str = new List<string>();
                string[] ReadText = File.ReadAllLines(dir, Encoding.Default);
                if (ReadText != null)
                {
                    foreach (string item in ReadText)
                    {
                        for (int i = 0; i < str.Length; i++)
                        {
                            if (item.Contains(str[i]))//搜索指定字符串ZZZ
                            {
                                Str.Add(item);//搜索到的内容存入ZzzString集合
                            }
                        }
                    }
                    out_str = Str.ToArray();
                    return 0;
                }
                else
                {
                    out_str = null;
                    return 2;
                }
            }
            catch (Exception er)
            {
                out_str = null;
                return 1;
            }
        }

        //private static SettingPara SetPara => GlobalObject.MachineInstant.SettingPara;

        public string Get(string sn)
        {
            String Address = "http://172.24.253.55/APIMD8/HBAPI/api.ashx?";
            String Type = "35";
            String _Action = "start";
            String Station = "PLaserMark";
            String Uid = "23428";
            String Pwd = "123";
            String Nopwd = "1";
            String ToolName = "AutoPacking";
            String IP = "172.27.113.67";

            string requestUriString = $"{Address}type={Type}&action={_Action}&sn={sn}&station={Station}&uid={Uid}&pwd={Pwd}&nopwd={Nopwd}&ToolName={ToolName}&IP={IP}";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUriString);
            httpWebRequest.Proxy = null;
            httpWebRequest.KeepAlive = false;
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "application/json; charset=UTF-8";
            httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            httpWebResponse?.Close();
            httpWebRequest?.Abort();
            return result;
        }

        public string Post(string Url, string Data, string Referer)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
            httpWebRequest.Method = "POST";
            httpWebRequest.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = bytes.Length;
            Stream requestStream = httpWebRequest.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            requestStream.Close();
            httpWebResponse?.Close();
            httpWebRequest?.Abort();
            return result;
        }


        public void Serialize<T>(T source)//序列化方法
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if (Object.ReferenceEquals(source, null))
            {
                return;
            }

            using (FileStream fs = new FileStream("D:\\Person.adc", FileMode.Create))//创建一个文件流，对文件进行写入
            {
                BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                bf.Serialize(fs, source); //序列化到硬盘
                fs.Close();//关闭文件流
            }
        }
        public T Deserialize<T>()
        {

            using (FileStream fs = new FileStream("D:\\Person.adc", FileMode.Open))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                return (T)binaryFormatter.Deserialize(fs);
            }
        }


    }
}
